<?php

/**
 * 夏日葵电商系统
 * http://www.xiarikui.com
 */

namespace Xcx\Model;

use Think\Model\RelationModel;

/**
 * Class QuestionModel
 * @package Home\Model
 */
class SearchModel extends RelationModel {

    public  $tableName = 'search_history';

    public function __construct() {
        parent::__construct();
        $this->user_id = session('user_id');
    }

    public function getInfoById($id) {
        $id = $id ? $id : 0;
        return M('search_history')
            ->where('id = '.$id)->find();
    }

    public function getListByUser() {
        return M('search_history')->where('user_id = '.$this->user_id)->order('add_time desc')->select();
    }

    public function addHistory($content) {
        $count = M('search_history')->where(" title = '$content' and user_id = ".$this->user_id)->count();
        if($count > 0){
            return true;
        }

        $select = M('search_history')->where("user_id = ".$this->user_id)->order('add_time asc')->select();
        if(count($select) > 5){
            M('search_history')->where("id = ".$select[0]['id'])->delete();
        }
        return M('search_history')->data(array(
            'title' => $content,
            'user_id' => $this->user_id,
            'add_time' => time(),
        ))->add();
    }

    public function delInfoById($id = 0){
        if($id == 'all'){
            M('search_history')->where('user_id = '.$this->user_id)->delete();
            return $this->getListByUser();
        }else{
            M('search_history')->where('id = '.$id)->delete();
            return $this->getListByUser();
        }
    }
}
